package com.lal.sdk.security;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class TokenManager {
    private final Map<String, TokenInfo> tokenStore = new ConcurrentHashMap<>();
    private final long tokenValidityMs;
    
    public TokenManager() {
        this(24 * 60 * 60 * 1000); // 24小时默认有效期
    }
    
    public TokenManager(long tokenValidityMs) {
        this.tokenValidityMs = tokenValidityMs;
    }
    
    public String createToken(String streamName, String clientIp) {
        String token = UUID.randomUUID().toString().replace("-", "");
        long expiryTime = System.currentTimeMillis() + tokenValidityMs;
        
        TokenInfo tokenInfo = new TokenInfo(token, streamName, clientIp, expiryTime);
        tokenStore.put(token, tokenInfo);
        
        return token;
    }
    
    public boolean validateToken(String token, String streamName, String clientIp) {
        TokenInfo tokenInfo = tokenStore.get(token);
        if (tokenInfo == null) {
            return false;
        }
        
        // 检查是否过期
        if (System.currentTimeMillis() > tokenInfo.getExpiryTime()) {
            tokenStore.remove(token);
            return false;
        }
        
        // 检查流名称匹配
        if (!tokenInfo.getStreamName().equals(streamName)) {
            return false;
        }
        
        // 检查IP地址匹配（可选）
        if (clientIp != null && !clientIp.equals(tokenInfo.getClientIp())) {
            return false;
        }
        
        return true;
    }
    
    public void revokeToken(String token) {
        tokenStore.remove(token);
    }
    
    public void cleanupExpiredTokens() {
        long currentTime = System.currentTimeMillis();
        tokenStore.entrySet().removeIf(entry -> 
            currentTime > entry.getValue().getExpiryTime()
        );
    }
    
    private static class TokenInfo {
        private final String token;
        private final String streamName;
        private final String clientIp;
        private final long expiryTime;
        
        public TokenInfo(String token, String streamName, String clientIp, long expiryTime) {
            this.token = token;
            this.streamName = streamName;
            this.clientIp = clientIp;
            this.expiryTime = expiryTime;
        }
        
        public String getToken() { return token; }
        public String getStreamName() { return streamName; }
        public String getClientIp() { return clientIp; }
        public long getExpiryTime() { return expiryTime; }
    }
}